package com.example.myapplication;

import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.lang.ref.WeakReference;

public class SplashActivity extends AppCompatActivity {
    private VideoView videoView;
    private TextView countdownTextView;
    private ImageButton closeButton;
    private Handler handler;
    private Runnable timeoutRunnable;
    private Runnable countdownRunnable;
    private int remainingSeconds;
    private boolean isVideoFinished = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_splash);


        // 初始化UI组件
        videoView = findViewById(R.id.videoView);
        countdownTextView = findViewById(R.id.countdownTextView);
        closeButton = findViewById(R.id.closeButton);

        // 设置倒计时组件点击事件
        ViewGroup countdownContainer = findViewById(R.id.countdownContainer);
        countdownContainer.setOnClickListener(v -> navigateToMainActivity());
        View closeButton = findViewById(R.id.closeButton);
        closeButton.setOnClickListener(v -> navigateToMainActivity());

        // 设置视频路径
        Uri videoUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.bjsp);
        videoView.setVideoURI(videoUri);
        videoView.start();

        // 使用静态内部类避免内存泄漏
        handler = new Handler(Looper.getMainLooper());
        timeoutRunnable = new TimeoutRunnable(this);

        // 动态获取视频时长并设置倒计时
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        retriever.setDataSource(this, videoUri);
        String durationStr = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        int videoDuration = Integer.parseInt(durationStr);
        remainingSeconds = (videoDuration / 1000) + 1; // 向上取整获取秒数

        // 启动倒计时
        startCountdown();

        // 启动超时计时器（增加1秒缓冲时间）
        handler.postDelayed(timeoutRunnable, videoDuration + 1000);

        // 监听视频播放完成事件
        videoView.setOnCompletionListener(mp -> {
            isVideoFinished = true;
            if (mp != null) {
                mp.release();
            }
            handler.removeCallbacks(timeoutRunnable);

            // 如果倒计时还未结束，继续显示直到结束
            if (remainingSeconds > 0) {
                showToast("视频播放完毕，" + remainingSeconds + "秒后进入应用");
            } else {
                navigateToMainActivity();
            }
        });

        // 监听视频播放错误事件
        videoView.setOnErrorListener((mp, what, extra) -> {
            Log.e("SplashActivity", "视频播放错误: what=" + what + ", extra=" + extra);
            if (mp != null) {
                mp.release();
            }
            cleanupAndNavigate(2000); // 2秒后跳转
            return true;
        });
    }

    private void startCountdown() {
        updateCountdownText();
        countdownRunnable = new Runnable() {
            @Override
            public void run() {
                if (remainingSeconds > 0) {
                    remainingSeconds--;
                    updateCountdownText();
                    handler.postDelayed(this, 1000);
                } else {
                    // 倒计时结束且视频已完成时跳转
                    if (isVideoFinished) {
                        navigateToMainActivity();
                    }
                }
            }
        };
        handler.postDelayed(countdownRunnable, 1000);
    }

    private void updateCountdownText() {
        if (countdownTextView != null) {
            countdownTextView.setText("跳过 " + remainingSeconds + "s");
        }
    }

    private void navigateToMainActivity() {
        if (!isFinishing() && !isDestroyed()) {
            cleanupResources();
            Intent intent = new Intent(SplashActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
    }

    private void cleanupAndNavigate(int delayMillis) {
        handler.removeCallbacksAndMessages(null);
        if (videoView != null) {
            videoView.stopPlayback();
        }
        showToast("视频加载失败，即将进入应用");
        handler.postDelayed(this::navigateToMainActivity, delayMillis);
    }

    private void cleanupResources() {
        handler.removeCallbacksAndMessages(null);
        if (videoView != null) {
            videoView.stopPlayback();
        }
    }

    private void showToast(String message) {
        Toast.makeText(this, "messgae", Toast.LENGTH_SHORT).show();
    }

    private static class TimeoutRunnable implements Runnable {
        private final WeakReference<SplashActivity> activityRef;

        public TimeoutRunnable(SplashActivity activity) {
            this.activityRef = new WeakReference<>(activity);
        }

        @Override
        public void run() {
            SplashActivity activity = activityRef.get();
            if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
                if (!activity.isVideoFinished) {
                    activity.isVideoFinished = true;
                    if (activity.remainingSeconds <= 0) {
                        activity.navigateToMainActivity();
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cleanupResources();
    }
}
